package com.fable.sp.core.controller;

import com.fable.sp.core.widget.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * .
 *
 * @author stormning on 16/8/10.
 */
public class WidgetRequestDispcher {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmartPageController.class);

    //request dispatcher
    public void processWidgetRequest(WidgetRequest request, WidgetResponse response) throws WidgetException, IOException {
        long startTime = System.currentTimeMillis();
        Throwable failureCause = null;

        // Expose current RequestAttributes to current thread.
        try {
            String phase = (String) request.getAttribute(WidgetRequest.LIFECYCLE_PHASE);
            if (WidgetRequest.ACTION_PHASE.equals(phase)) {
                doActionService((ActionRequest) request, (ActionResponse) response);
            } else if (WidgetRequest.RENDER_PHASE.equals(phase)) {
                doRenderService((RenderRequest) request, (RenderResponse) response);
            } else if (WidgetRequest.EVENT_PHASE.equals(phase)) {
                doEventService((EventRequest) request, (EventResponse) response);
            } else {
                throw new IllegalStateException("Invalid widget request phase: " + phase);
            }
        } catch (WidgetException | IOException ex) {
            failureCause = ex;
            throw ex;
        } catch (Throwable ex) {
            failureCause = ex;
            throw new WidgetException("Request processing failed", ex);
        } finally {
            if (failureCause != null) {
                LOGGER.error("Could not complete request", failureCause);
            } else {
                LOGGER.debug("Successfully completed request");
            }
            // Whether or not we succeeded, publish an event.
            long processingTime = System.currentTimeMillis() - startTime;
            LOGGER.info("Processing time {}", processingTime);
            //publish request handled event TODO
        }
    }

    private void doEventService(EventRequest request, EventResponse response) throws WidgetException, IOException {

    }

    private void doRenderService(RenderRequest request, RenderResponse response) throws WidgetException, IOException {

    }

    private void doActionService(ActionRequest request, ActionResponse response) throws WidgetException, IOException {

    }


}
